package com.uhylab.uhuvinetest.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.bean.History_Content;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 项目名称：Uhylab
 * 类描述：
 * 创建人：xyb
 * 创建时间：16/8/29 18:00
 * 修改人：xyb
 * 修改时间：16/8/29 18:00
 * 修改备注：
 */
public class UHCYDoctorActivity extends UHBaseActivity {
    @BindView(R.id.webView_doctor)
    WebView mWebViewDoctor;
    private Handler mHandler;
    private long id;
    private String userToken;
    private static final int INIT_WEBVIEW_ID = 1;
    private static final int LOD_WEBVIEW_ID = 2;
    private ArrayList<History_Content> arrayListContent;
    private String cyDoctor;
    private String problem_id;
    private boolean isCreate;

    @Override
    public int bindLayout() {
        return R.layout.activity_uhcydoctor;
    }

    @Override
    public void initView(View view) {
        ButterKnife.bind(this);
        Intent intent = getIntent();
        id = intent.getLongExtra("id", 0L);
        userToken = intent.getStringExtra("token");
        isCreate = intent.getBooleanExtra("isCreate", false);
        try {
            problem_id = intent.getStringExtra("problem_id");
        } catch (Exception e) {
            e.printStackTrace();
        }

        arrayListContent = intent.getParcelableArrayListExtra("content");
        try {
            if (arrayListContent != null && arrayListContent.size() > 0) {
                cyDoctor = "我的问题ID是" + id;
                for (History_Content history_content : arrayListContent) {
                    String name = history_content.getName();
                    String content = history_content.getContent();
                    cyDoctor += name;
                    cyDoctor += content;
                }
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doBusiness(Context mContext) {
        initHandler();
        initWebView();

        initNetWork();


    }

    private void initNetWork() {
        OkHttpUtils.get()
                .url(UHBase.chunYuDoctorApi)
                .addParams("token", userToken)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.get("code").equals("0000")) {
                                Message message = new Message();
                                message.what = INIT_WEBVIEW_ID;
                                message.obj = jsonObject.get("data");
                                mHandler.sendMessage(message);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mWebViewDoctor.getSettings().setJavaScriptEnabled(true);
        mWebViewDoctor.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        mWebViewDoctor.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
    }

    /**
     * 初始化
     */
    private void initHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case INIT_WEBVIEW_ID:
                        mWebViewDoctor.loadUrl((String) message.obj);
                        mWebViewDoctor.setWebViewClient(new WebViewClient() {
                            @Override
                            public void onPageFinished(WebView view, String url) {
                                if (isCreate) {

                                    mWebViewDoctor.loadUrl("http://www.chunyuyisheng.com/cooperation/wap/problem_detail_page/?partner=yunyanxing&problem_id=" + problem_id);
                                    mWebViewDoctor.setWebViewClient(new WebViewClient() {
                                        @Override
                                        public void onPageFinished(WebView view, String url) {
                                            super.onPageFinished(view, url);

                                        }
                                    });
                                } else {
                                    final String url1 = getFromAssets("index.js");
                                    mWebViewDoctor.loadUrl("http://www.chunyuyisheng.com/cooperation/wap/create_free_problem_page/?partner=yunyanxing");
                                    mWebViewDoctor.setWebViewClient(new WebViewClient() {
                                        @Override
                                        public void onPageFinished(WebView view, String url) {
                                            mWebViewDoctor.loadUrl("javascript:" + url1);
                                            mWebViewDoctor.setWebViewClient(new WebViewClient(){
                                                @Override
                                                public void onPageFinished(WebView view, String url) {
                                                    super.onPageFinished(view, url);
                                                }
                                            });
                                            mHandler.sendEmptyMessageDelayed(LOD_WEBVIEW_ID, 1000);
                                        }
                                    });


                                }


                            }
                        });
                        break;
                    case LOD_WEBVIEW_ID:
                        mWebViewDoctor.loadUrl("javascript:createFreeProblem(\"" + cyDoctor + "\", \"" + "男" + "\", \"+" + "23" + "\",\"" + Long.toString(id) +
                                "\",\"" + userToken +
                                "\")");
                        mWebViewDoctor.setWebViewClient(new WebViewClient(){
                            @Override
                            public void onPageFinished(WebView view, String url) {
                                super.onPageFinished(view, url);
                            }
                        });
                        break;
                }

                return true;
            }
        });
    }

    @Override
    public void resume() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void onBackPressed() {
        if (mWebViewDoctor.canGoBack()) {
            mWebViewDoctor.goBack();
        } else {
            finish();
        }
    }

    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
